<?php

class Ping{	function httpPost( $host, $port, $uri, $data )	{		$url = "http://${host}:${port}${uri}";		$fp = @fsockopen( $host, $port, $errno, $errstr, 5);		if (!$fp)		return false;
		
		$userAgent = $_SERVER['HTTP_USER_AGENT'];		$out = "POST ${uri} HTTP/1.1\r\n";
		$out .= "User-Agent: ${userAgent}\r\n";		$out .= "Host: ${host}\r\n";		$out .= "Content-Type: text/xml\r\n";		$out .= "Content-Length: ". strlen($data). "\r\n";		fwrite($fp, $out);		fwrite($fp, "\r\n");		fwrite($fp, $data);		fwrite($fp, "\r\n");		fpassthru($fp);		fclose($fp);		return true;	}}	
function technoRati( $title, $url )
{	$uTitle = htmlspecialchars($title);	$uUrl = htmlspecialchars($url);	$xml = "<?xml version=\"1.0\"?>\n";	$xml .= "<methodCall>\n";	$xml .= "<methodName>weblogUpdates.ping</methodName>\n";	$xml .= "<params>\n";
	$xml .= "<param>\n<value>$uTitle</value>\n</param>\n";	$xml .= "<param>\n<value>$uUrl</value>\n</param>\n";	$xml .= "</params>\n";	$xml .= "</methodCall>\n";	Ping::httpPost( "rpc.technorati.com", 80, "/rpc/ping", $xml );}

function create_room ($roomname, $desc, $skill, $gametype, $host, $time)
{
 	 $adding = date("G");	
	 $addedtime = $time + $adding;
	 if ($addedtime > 23) { $time = $addedtime - 24; $gamedate = strtotime('tomorrow'); } else {$time = $addedtime; $gamedate = strtotime('today');}
	 $time = $time . ':00';
 	 $gamedate = date("F j, Y", $gamedate);
     $query = "insert into gamematch (battlename, descr, skill, gametype, host, matchtime, matchdate) values ('$roomname', '$desc', '$skill', '$gametype', '$host', '$time', '$gamedate')";
     mysql_query ($query) or die ($sql.' failed because '.mysql_error());

	 include 'rss.php';	 $url = "http://www.mariokartchallenger.com";
	 $title = "Wii Friend Codes, Online Racing, Battle Mode | MARIO KART CHALLENGER";	 technoRati ($title, $url);
}

function stringtoarray($string)
{
	$len = strlen($string);

	$cur = 0;

	$characterarray = array();

	while($cur < $len){
		$char = $string{$cur};
		array_push($characterarray,$char);
		$cur = $cur + 1;
	}

	return $characterarray;

}

function diffTime($bigTime,$smallTime){//input format hh:mm:ss        list($h1,$m1,$s1)=split(":",$bigTime);        list($h2,$m2,$s2)=split(":",$smallTime);               $second1=$s1+($h1*3600)+($m1*60);//converting it into seconds        $second2=$s2+($h2*3600)+($m2*60);                      if ($second1==$second2)        {            $resultTime="00:00:00";            return $resultTime;            exit();        }                             if ($second1<$second2) //        {            $second1=$second1+(24*60*60);//adding 24 hours to it.        }                             $second3=$second1-$second2;               //print $second3;        if ($second3==0)        {            $h3=0;        }        else        {            $h3=floor($second3/3600);//find total hours        }                   $remSecond=$second3-($h3*3600);//get remaining seconds        if ($remSecond==0)        {            $m3=0;        }        else        {            $m3=floor($remSecond/60);// for finding remaining  minutes        }                   $s3=$remSecond-(60*$m3);               if($h3==0)//formating result.        {            $h3="00";        }        if($m3==0)        {            $m3="00";        }        if($s3==0)        {            $s3="00";        }                   $resultTime="$h3:$m3:$s3";                      return $resultTime;}
// Salt Generatorfunction generate_salt(){     // Declare $salt     $salt = '';     // And create it with random chars     for ($i = 0; $i < 3; $i++)     {          $salt .= chr(rand(35, 126));     }          return $salt;}

function generate_malt(){     // Declare $malt     $malt = 'weegee';     return $malt;}

function check_email_address($email) 
{	// First, we check that there's one @ symbol, and that the lengths are right	if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) {return false;}	 
    // Split it into sections to make life easier	$email_array = explode("@", $email);	$local_array = explode(".", $email_array[0]);

	for ($i = 0; $i < sizeof($local_array); $i++) {		if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i])) {		return false;		}	}

	if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name	$domain_array = explode(".", $email_array[1]);	if (sizeof($domain_array) < 2) {		return false; // Not enough parts to domain	}

	for ($i = 0; $i < sizeof($domain_array); $i++) {		if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])) {		return false;	}	}	}	return true;}

function reset_password($username, $password){     $query = "select salt from user where username='$username' limit 1";     $result = mysql_query($query);

     $user = mysql_fetch_array($result);

     // Using the salt, encrypt the given password to see if it     // matches the one in the database     $encrypted = md5(md5($password).$user['salt']);
     // And lastly, store the information in the database
	 $query = mysql_query("UPDATE user SET password = '$encrypted' WHERE username = '$username'");     mysql_query ($query);

  	 $to = "w$username@wii.com";	 $from = "mii@mariokartchallenger.com";	 $subject = "Password Reset";	 $message = "Your new password is: $password\n\n\n-The Mario Kart Challenger Team";	 mail($to, $subject, $message, "From: $from\r\nReply-to: $from\r\n");
}

function email_match($username, $friendcode, $nick, $matchname, $matchtime)
{

	 $matchtime = date("gA", strtotime($matchtime));

  	 $to = "w$username@wii.com";	 $from = "mii@mariokartchallenger.com";	 $subject = "$friendcode - $matchtime";	 $message = "$matchname - $matchtime\n\nWhat's going on, $nick has added you as a friend and is ready to game... Please add the friend code number $friendcode so you can connect.\n\n\n-The Mario Kart Challenger Team";	 mail($to, $subject, $message, "From: $from\r\nReply-to: $from\r\n");
}
function user_register($username, $password, $nick, $skill, $racer, $country, $friendcode){     $salt = generate_salt();     $encrypted = md5(md5($password).$salt);

	 $today = date("F j, Y");

	 $passcode = mt_rand(10000, 99999);

	 $query = "insert into user (username, password, nick, skill, racer, salt, joindate, passcode, battlevr, racevr, country, gamecode) values ('$username', '$encrypted', '$nick', '$skill', '$racer', '$salt', '$today', '$passcode', '5000', '5000', '$country', '$friendcode')";     mysql_query ($query) or die ('Overload... try registering again.');

}

function edit_user($username, $password, $nick, $gamecode, $battlevr, $racevr, $racer){     $query = "select * from user where username='$username'";     $result = mysql_query($query);

     $user = mysql_fetch_array($result);
	 $lasttry = $user['userid'];
     // And lastly, store the information in the database
     if (!empty($password) && !empty($gamecode)) { $encrypted=md5(md5($password).$user['salt']); $query = "UPDATE user SET password='$encrypted', nick='$nick', gamecode='$gamecode', battlevr='$battlevr', racevr='$racevr', racer='$racer' WHERE userid = '$lasttry'";}
	 elseif (empty($password) && empty($gamecode)) { $query = "UPDATE user SET nick = '$nick', battlevr='$battlevr', racevr='$racevr', racer = '$racer' WHERE userid = '$lasttry'";}
	 elseif (!empty($password) && empty($gamecode)) { $encrypted = md5(md5($password).$user['salt']); $query = "UPDATE user SET password = '$encrypted', nick = '$nick', battlevr='$battlevr', racevr='$racevr', racer = '$racer' WHERE userid = '$lasttry'";}
	 elseif (empty($password) && !empty($gamecode)) { $query = "UPDATE user SET nick = '$nick', gamecode = '$gamecode', battlevr='$battlevr', racevr='$racevr', racer = '$racer' WHERE userid = '$lasttry'";}     mysql_query ($query);}

function user_login($username, $password){     // Try and get the salt from the database using the username     $query = "select salt from user where username='$username' limit 1";     $result = mysql_query($query);     if (mysql_num_rows($result) > 0)     {          // Get the user          $user = mysql_fetch_array($result);          // Using the salt, encrypt the given password to see if it          // matches the one in the database          $encrypted_pass = md5(md5($password).$user['salt']);          // Try and get the user using the username & encrypted pass          $query = "select userid, username from user where username='$username' and password='$encrypted_pass'";          $result = mysql_query($query);          if (mysql_num_rows($result) > 0)          {               $user = mysql_fetch_array($result);               // Now encrypt the data to be stored in the session               $encrypted_id = md5($user['userid']);               $encrypted_name = md5($user['username']);                              // Store the data in the session               $_SESSION['userid'] = $userid;               $_SESSION['username'] = $username;               $_SESSION['encrypted_id'] = $encrypted_id;               $_SESSION['encrypted_name'] = $encrypted_name;
			   $lastlogin = time();
			   $userid = $user['userid'];
			   $query = mysql_query("UPDATE user SET lastlogin = '$lastlogin' WHERE userid = '$userid'");		       mysql_query ($query);

		       $today = date("F j, Y");

			   $query = "SELECT date FROM sitemap WHERE id = '1'";		       $result = mysql_query ($query);
		       $sitemap = mysql_fetch_array($result);
			   $lastupdate = $sitemap['date'];

			   if ($today != $lastupdate) { 
					$query = mysql_query("UPDATE sitemap SET date = '$today' WHERE id = '1'");			        mysql_query ($query);
					include 'sitemapgen.php';
			   }
				
			   $ip = $_SERVER['REMOTE_ADDR'];

			   $query = mysql_query("INSERT INTO ip (userid, ip) VALUES ('$username', '$ip')");		       mysql_query ($query);
		                      // Return ok code               return 'Correct';          }          else          {               return 'Invalid Password';          }     }     else     {          return 'Invalid Username';     }}function user_logout(){     // End the session and unset all vars     session_unset ();     session_destroy ();}

function is_joined($username, $roomno){
 	 $query = "select * from gamematch where id='$roomno'";     $result = mysql_query($query); 
	 $roomstuff = mysql_fetch_array($result);      if ($username == $roomstuff['host'])     {          return true;     }     else if ($username == $roomstuff['seat2'])     {          return true;     }
     else if ($username == $roomstuff['seat3'])     {          return true;     }
     else if ($username == $roomstuff['seat4'])     {          return true;     }
     else if ($username == $roomstuff['seat5'])     {          return true;     }
	 else { return false; }}function is_authed(){     // Check if the encrypted username is the same     // as the unencrypted one, if it is, it hasn't been changed     if (isset($_SESSION['username']) && (md5($_SESSION['username']) == $_SESSION['encrypted_name']))     {          return true;     }     else     {          return false;     }}
?>